package com.wenjiang.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wenjiang.common.dto.CommentParams;
import com.wenjiang.common.dto.GoodCommentParams;
import com.wenjiang.common.lang.Result;
import com.wenjiang.common.vo.BeReplyVo;
import com.wenjiang.common.vo.CommentVo;
import com.wenjiang.common.vo.GoodCommentVo;
import com.wenjiang.common.vo.ReplyVo;
import com.wenjiang.entity.MallComment;
import com.wenjiang.mapper.MallCommentMapper;
import com.wenjiang.mapper.MallReplyMapper;
import com.wenjiang.service.MallCommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author lwj
 * @since 2021-10-23
 */
@Service
public class MallCommentServiceImpl extends ServiceImpl<MallCommentMapper, MallComment> implements MallCommentService {


    @Autowired
    MallCommentMapper mallCommentMapper;

    @Autowired
    MallReplyMapper mallReplyMapper;

    @Override
    public Result getUserComment(Long userId) {
        //查询用户所有的评价
        return Result.succ(mallCommentMapper.getUserComment(userId));
    }


    @Override
    public Result commentGood(CommentParams commentParams) {
        UpdateWrapper<MallComment> updateWrapper = new UpdateWrapper<>();
        updateWrapper.set("comment_content", commentParams.getCommentContent());
        updateWrapper.set("star", commentParams.getStar());
        updateWrapper.set("is_comment", 1 );
        //添加用户评论
        updateWrapper.set("created_time", LocalDateTime.now());
        updateWrapper.eq("comment_id", commentParams.getCommentId());
        mallCommentMapper.update(null,updateWrapper);
        return Result.succ("评论成功!");
    }


    //获取某个商品的回复
    @Override
    public Result getGoodComment(GoodCommentParams goodCommentParams) {

        //查询的起始个数

        int index= (goodCommentParams.getCurrentPage()-1)*goodCommentParams.getPageSize();
        goodCommentParams.setCurrentPage(index);


        //查看商品评论
        List<GoodCommentVo> goodComment = mallCommentMapper.getGoodComment(goodCommentParams);

        //遍历商品评论 查找该评论下的回复
        for(GoodCommentVo gc: goodComment){
            //查找该商品下的1级回复
            List<ReplyVo> replyVos = mallReplyMapper.getCommentReply(gc.getCommentId());
            //遍历回复中的回复（二级回复)
            for(ReplyVo reply:replyVos){
                List<BeReplyVo> beReply = mallReplyMapper.getBeReply(reply.getReplyId());
                //设置二级回复
                reply.setReplyVos(beReply);
            }
            //设置一级回复
            gc.setReplyVoList(replyVos);
        }


        return Result.succ(goodComment);
    }
}
